import { ref, watch } from 'vue'
import { readFileUrl } from '@/utils'

/** 获取图片地址 */
export default function useImageUrl(params: { src: string; file?: File }) {
  /** 图片地址 */
  const url = ref(params.src || '')

  /** 图片加载 */
  const loading = ref(false)

  watch(
    () => params.src,
    src => (url.value = src),
    { immediate: true }
  )

  watch(
    () => params.file,
    async file => {
      if (params.src || !file) return

      loading.value = true
      try {
        url.value = await readFileUrl(file)
      } finally {
        loading.value = false
      }
    },
    { immediate: true }
  )

  return { url, loading }
}
